package com.hna.face.config;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;

@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig implements EnvironmentAware {

	@Autowired
	private MybatisProperties properties;

	@Autowired
	private ResourceLoader resourceLoader;

	@Autowired(required = false)
	private Interceptor[] interceptors;

	@Autowired(required = false)
	private DatabaseIdProvider databaseIdProvider;

	private RelaxedPropertyResolver propertyResolver;
	
//	private AlgorithmUtil algorithmUtil;

	@Override
	public void setEnvironment(Environment env) {
		propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
    }

	@Bean
	public DataSource dataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(propertyResolver.getProperty("url"));
		datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
		datasource.setUsername(propertyResolver.getProperty("username"));
		try {
			datasource.setPassword(propertyResolver.getProperty("password"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		datasource.setPassword(propertyResolver.getProperty("password"));
		datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
		datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
		datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait")));
		datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active")));
		datasource.setMinEvictableIdleTimeMillis(
				Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
		try {
			datasource.setFilters("stat,wall");
		}
		catch (SQLException e) {
			throw new IllegalArgumentException("Failed to create dataSource: " + e.getMessage(), e);
		}
		return datasource;
	}

	/**
	 * mybatis-plus分页插件
	 */
	@Bean
	public PaginationInterceptor paginationInterceptor() {
		PaginationInterceptor page = new PaginationInterceptor();
		page.setDialectType("sqlserver");
		return page;
	}

	/**
	 * 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定 配置文件和mybatis-boot的配置文件同步
	 */
	@Bean
	public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
		MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
		mybatisPlus.setDataSource(dataSource());
		mybatisPlus.setVfs(SpringBootVFS.class);
		if (StringUtils.hasText(properties.getConfigLocation())) {
			mybatisPlus.setConfigLocation(resourceLoader.getResource(properties.getConfigLocation()));
		}
		mybatisPlus.setConfiguration(properties.getConfiguration());
		if (!ObjectUtils.isEmpty(interceptors)) {
			mybatisPlus.setPlugins(interceptors);
		}
		// MP 全局配置，更多内容进入类看注释
		GlobalConfiguration globalConfig = new GlobalConfiguration();
		// 配置公共字段自动填写
		// globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());
		globalConfig.setDbType(DBType.MYSQL.name());
		// ID 策略 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID")
		globalConfig.setIdType(0);
		mybatisPlus.setGlobalConfig(globalConfig);
		MybatisConfiguration mc = new MybatisConfiguration();
		mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
		mybatisPlus.setConfiguration(mc);
		if (databaseIdProvider != null) {
			mybatisPlus.setDatabaseIdProvider(databaseIdProvider);
		}
		if (StringUtils.hasLength(properties.getTypeAliasesPackage())) {
			mybatisPlus.setTypeAliasesPackage(properties.getTypeAliasesPackage());
		}
		if (StringUtils.hasLength(properties.getTypeHandlersPackage())) {
			mybatisPlus.setTypeHandlersPackage(properties.getTypeHandlersPackage());
		}
		if (!ObjectUtils.isEmpty(properties.resolveMapperLocations())) {
			mybatisPlus.setMapperLocations(properties.resolveMapperLocations());
		}
		return mybatisPlus;
	}
}
